/*
 * Copyright 2010-2011 Mike Novak <michael.novakjr@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.codeversed.plugins.buzz.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;

import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.codeversed.plugins.buzz.R;
import com.codeversed.plugins.buzz.util.BuzzUtils;
import com.codeversed.plugins.buzz.util.Constants;
import com.codeversed.plugins.buzz.util.HttpUtils;
import com.codeversed.plugins.buzz.widget.CommentsAdapter;

import java.lang.ref.WeakReference;

public class CommentListActivity extends Activity {
    protected static final int DIALOG_COMMENT = 0x1;
    protected static final int DIALOG_POST_COMMENT = 0x2;
    protected static final int DIALOG_COMMENT_ERROR = 0x3;
    protected static final int DIALOG_NO_NETWORK = 0x4;
    protected static final int DIALOG_EMPTY_COMMENT = 0x5;
    
    private String mToken;
    private String mTokenSecret;
    private String mActivityId;

    private ListView mCommentListView;
    private TextView mEmptyView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commentlist);

        mCommentListView = (ListView) findViewById(R.id.comment_list_view);
        mEmptyView = (TextView) findViewById(R.id.comment_empty_view);

        Intent intent = getIntent();
        mActivityId = intent.getStringExtra("id");

        SharedPreferences prefs = getSharedPreferences("buzz_oauth.prefs", Context.MODE_PRIVATE);
        mToken = prefs.getString(Constants.PREF_TOKEN, "");
        mTokenSecret = prefs.getString(Constants.PREF_TOKEN_SECRET, "");
        
        if (mActivityId != null) {
            CommentsDownloadTask task = new CommentsDownloadTask(mCommentListView, mEmptyView);
            task.execute(mActivityId, mToken, mTokenSecret);

            mEmptyView.setText("Loading...");
            mEmptyView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected Dialog onCreateDialog(int id, Bundle args) {
        AlertDialog.Builder builder;

        switch (id) {
        case DIALOG_COMMENT:
            builder = new AlertDialog.Builder(this);
            builder.setTitle(getString(R.string.dialog_comment_title));

            View view = getLayoutInflater().inflate(R.layout.dialog_comment, null, false);
            builder.setView(view);

            DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                    case DialogInterface.BUTTON_NEGATIVE:
                        dialog.dismiss();
                        break;
                    case DialogInterface.BUTTON_POSITIVE:
                        dialog.dismiss();

                        Dialog d = (Dialog) dialog;
                        EditText commentEntry = (EditText) d.findViewById(R.id.dialog_comment_entry);
                        String comment = commentEntry.getText().toString();

                        if (TextUtils.isEmpty(comment.trim())) {
                            showDialog(DIALOG_EMPTY_COMMENT);
                            return;
                        }

                        if (!HttpUtils.isConnectedToNetwork(CommentListActivity.this)) {
                            showDialog(DIALOG_NO_NETWORK);
                            return;
                        }

                        showDialog(DIALOG_POST_COMMENT);

                        /* execute the async task to post a comment. */
                        PostCommentTask task = new PostCommentTask(CommentListActivity.this);
                        task.execute(comment, mActivityId, mToken, mTokenSecret);
                        break;
                    default:
                        Log.d(Constants.LOG_TAG, "Weird button selection: " + which);
                    }
                }
            };

            DialogInterface.OnDismissListener dismissListener = new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    Dialog d = (Dialog) dialog;
                    EditText commentEntry = (EditText) d.findViewById(R.id.dialog_comment_entry);
                    commentEntry.setText("");
                }
            };

            builder.setNegativeButton(R.string.cancel_button, dialogListener);
            builder.setPositiveButton(R.string.comment_button, dialogListener);
            Dialog d = builder.create();
            d.setOnDismissListener(dismissListener);

            return d;
        case DIALOG_POST_COMMENT:
            ProgressDialog dialog = new ProgressDialog(this);
    		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    		dialog.setMessage(getString(R.string.post_comment_label));
    		return dialog;
    	case DIALOG_NO_NETWORK:
    	    builder = new AlertDialog.Builder(this);
    	    builder.setTitle(getString(R.string.no_network_title));
    	    builder.setMessage(getString(R.string.no_network_message));
    	    builder.setNeutralButton(R.string.confirm_dialog, new DialogInterface.OnClickListener() {
    	        public void onClick(DialogInterface dialog, int which) {
    	            dialog.dismiss();
    	        }
    	    });
    	    return builder.create();
    	case DIALOG_EMPTY_COMMENT:
    	    builder = new AlertDialog.Builder(this);
    	    builder.setTitle(getString(R.string.no_comment_title));
    	    builder.setMessage(getString(R.string.no_comment_text));
    	    builder.setNeutralButton(R.string.confirm_dialog, new DialogInterface.OnClickListener() {
    	        public void onClick(DialogInterface dialog, int which) {
    	            dialog.dismiss();
    	        }
    	    });
    	    return builder.create();
    	case DIALOG_COMMENT_ERROR:
    	    builder = new AlertDialog.Builder(this);
    	    builder.setTitle(getString(R.string.comment_error_title));
    	    builder.setMessage(getString(R.string.comment_error_text));
    	    builder.setNeutralButton(R.string.confirm_dialog, new DialogInterface.OnClickListener() {
    	        public void onClick(DialogInterface dialog, int which) {
    	            dialog.dismiss();
    	        }
    	    });
    	    return builder.create();
        default:
            Log.e(Constants.LOG_TAG, "Unrecognized dialog request: " + id);
            return null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.comment_menu, menu);

        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.comment_item:
            showDialog(DIALOG_COMMENT);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    protected void refreshComments() {
        CommentsDownloadTask task = new CommentsDownloadTask(mCommentListView, mEmptyView);
        task.execute(mActivityId, mToken, mTokenSecret);
    }

    static class CommentsDownloadTask extends AsyncTask<String, Void, Cursor> {
        private final WeakReference<ListView> mListViewRef;
        private final WeakReference<TextView> mTextViewRef;

        public CommentsDownloadTask(ListView view, TextView emptyView) {
            mListViewRef = new WeakReference<ListView>(view);
            mTextViewRef = new WeakReference<TextView>(emptyView);
        }

        @Override
        protected Cursor doInBackground(String... params) {
            try {
                return BuzzUtils.requestActivityComments(params[0], params[1], params[2]);
            } catch (Exception e) {
                Log.e(Constants.LOG_TAG, "Error downloading comments: " + e.toString());
                return null;
            }
        }

        @Override
        protected void onPostExecute(Cursor cur) {
            if (cur == null) {
                return;
            }

            ListView view = mListViewRef.get();
            TextView emptyView = mTextViewRef.get();
            
            if (cur.getCount() == 0) {
                if (emptyView == null) {
                    return;
                }

                emptyView.setText("No comments.");
                emptyView.setVisibility(TextView.VISIBLE);
                view.setVisibility(ListView.GONE);
            } else {
                if (view == null) {
                    return;
                }

                view.setVisibility(ListView.VISIBLE);
                emptyView.setVisibility(TextView.GONE);
            }

            CommentsAdapter adapter = new CommentsAdapter(view.getContext(), cur);
            view.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }

    static class PostCommentTask extends AsyncTask<String, Void, Boolean> {
        private final WeakReference<CommentListActivity> mActivityRef;

        public PostCommentTask(CommentListActivity act) {
            mActivityRef = new WeakReference<CommentListActivity>(act);
        }

        @Override
        protected Boolean doInBackground(String... params) {
            try {
                return BuzzUtils.postComment(params[0], params[1], params[2], params[3]);
            } catch (Exception e) {
                Log.e(Constants.LOG_TAG, "Error posting comment: " + e.toString());
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean status) {
            CommentListActivity act = mActivityRef.get();
            act.dismissDialog(CommentListActivity.DIALOG_POST_COMMENT);

            if (status) {
                act.refreshComments();
            } else {
                act.showDialog(CommentListActivity.DIALOG_COMMENT_ERROR);
            }
        }
    }
}
